﻿using OMR.EasyBackup.Core.EventArguments;
using System.IO;

namespace OMR.EasyBackup.Core.Watchers
{
    public class FSWatcher : WatcherBase
    {
        private FileSystemWatcher fsw;

        public FSWatcher(string rootDirectory, string filter)
        {
            fsw = new FileSystemWatcher(rootDirectory);

            fsw.IncludeSubdirectories = true;
            fsw.InternalBufferSize = 1024 * 8 * 10;
            fsw.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite;

            fsw.Created += fsw_Created;
            fsw.Deleted += fsw_Deleted;
            fsw.Error += fsw_Error;
            fsw.Renamed += fsw_Renamed;
            fsw.Changed += fsw_Changed;
        }

        public override void Start()
        {
            fsw.EnableRaisingEvents = true;
        }

        public override void Stop()
        {
            fsw.EnableRaisingEvents = false;
        }

        private void fsw_Renamed(object sender, RenamedEventArgs e)
        {
            if (OnFileRenamed != null)
                OnFileRenamed.Invoke(this, new FileRenamedEventArgs(e.OldFullPath, e.FullPath));
        }

        private void fsw_Error(object sender, ErrorEventArgs e)
        {
            OnError.Invoke(this, e);
        }

        private void fsw_Deleted(object sender, FileSystemEventArgs e)
        {
            if (OnFileDeleted != null)
                OnFileDeleted.Invoke(this, new FileDeletedEventArgs(e.FullPath));
        }

        private void fsw_Created(object sender, FileSystemEventArgs e)
        {
            try
            {
                if (OnFileCreated != null)
                    OnFileCreated.Invoke(this, new FileCreatedEventArgs(e.FullPath, File.ReadAllBytes(e.FullPath)));
            }
            catch (System.Exception exception)
            {
                if (OnError != null)
                    OnError.Invoke(this, new ErrorEventArgs(exception));
            }
        }

        private void fsw_Changed(object sender, FileSystemEventArgs e)
        {
            try
            {
                if (OnFileContentChanged != null)
                    OnFileContentChanged(this, new FileContentChangedEventArgs(e.FullPath, File.ReadAllBytes(e.FullPath)));
            }
            catch (System.Exception exception)
            {
                if (OnError != null)
                    OnError.Invoke(this, new ErrorEventArgs(exception));
            }
        }
    }
}
